package com.appspot.mypartymanager.dao.impl;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.appspot.mypartymanager.dao.PMF;
import com.appspot.mypartymanager.dao.PartyDAO;
import com.appspot.mypartymanager.entity.Party;
import com.appspot.mypartymanager.exception.InvalidPartyException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class PartyDAOImpl implements PartyDAO {

	private static PartyDAOImpl instance = null;

	public static PartyDAOImpl getInstance() {

		if (instance == null) {
			instance = new PartyDAOImpl();
		}

		return instance;

	}

	private PartyDAOImpl() {
		super();
	}

	@Override
	public void createParty(Party newParty) throws InvalidPartyException {

		PersistenceManager pm = PMF.get().getPersistenceManager();

		pm.makePersistent(newParty);

		pm.close();

	}

	@Override
	public Party getPartyById(Long id) {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		Party party = pm.getObjectById(Party.class, id);

		pm.close();

		return party;
	}

	@Override
	public List<Party> getPartysByUser(String ownerUserGoogleAcount) {

		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query query = pm.newQuery(Party.class);
		query.setFilter("ownerUserGoogleAcount == ownerUserGoogleAcountParam");
		query.setOrdering("partyDate desc");
		query.declareParameters("String ownerUserGoogleAcountParam");

		@SuppressWarnings("unchecked")
		List<Party> parties = (List<Party>) query.execute(ownerUserGoogleAcount);

		query.closeAll();
		return parties;

	}

	@Override
	public void deleteParty(Long id) {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		Party partyToDelete = pm.getObjectById(Party.class, id);
		pm.deletePersistent(partyToDelete);
		pm.close();

	}

	@Override
	public void updateParty(Party partyToUpdate) throws InvalidPartyException {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		Party oldParty = pm.getObjectById(Party.class, partyToUpdate.getId());
		oldParty.setDateCreated(partyToUpdate.getDateCreated());
		oldParty.setOwnerGoogleAcount(partyToUpdate.getOwnerGoogleAcount());
		oldParty.setName(partyToUpdate.getName());
		oldParty.setAnnouncement(partyToUpdate.getAnnouncement());
		oldParty.setPartyDate(partyToUpdate.getPartyDate());
		oldParty.setPartyManagersGoogleAcounts(partyToUpdate
				.getPartyManagersGoogleAcounts());
		oldParty.setGoogleMapsAdress(partyToUpdate.getGoogleMapsAdress());
		oldParty.setAdress(partyToUpdate.getAdress());
		pm.close();

	}

}
